package io.kiki.sba.registry.server.metadata.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.GenericResponse;
import io.kiki.sba.registry.common.model.metaserver.DataOperation;
import io.kiki.sba.registry.common.model.metaserver.blacklist.RegistryForbiddenServerRequest;
import io.kiki.sba.registry.server.metadata.MetadataLeaderService;
import io.kiki.sba.registry.server.metadata.lease.filter.RegistryForbiddenServerManager;
import io.kiki.sba.registry.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


public class RegistryForbiddenServerHandler extends BaseMetaServerHandler<RegistryForbiddenServerRequest> {

    private static final Logger logger = LoggerFactory.getLogger(RegistryForbiddenServerHandler.class);

    @Autowired
    private RegistryForbiddenServerManager registryForbiddenServerManager;

    @Autowired
    private MetadataLeaderService metadataLeaderService;

    @Override
    public void checkParam(RegistryForbiddenServerRequest request) {
        StringUtil.checkNotBlank(request.getCell(), "cell");
        StringUtil.checkNotBlank(request.getIp(), "ip");
    }

    @Override
    public Object doHandle(Channel channel, RegistryForbiddenServerRequest request) {
        logger.info("[doHandle] from {}, request: {}", channel.getRemoteAddress().getHostName(), request);
        if (!metadataLeaderService.amILeader()) {
            buildFailedResponse("not leader");
        }
        DataOperation operation = request.getOperation();
        String ip = request.getIp();

        boolean success = false;
        switch (operation) {
        case add:
            success = registryForbiddenServerManager.addToBlacklist(request);
            break;
        case remove:
            success = registryForbiddenServerManager.removeFromBlacklist(request);
            break;
        default:
            break;
        }

        if (success) {
            return GenericResponse.buildSuccessResponse();
        }

        logger.error("forbidden server: {} operation:{} fail.", ip, operation);
        return GenericResponse.buildFailedResponse("handle forbidden server fail.");
    }

    @Override
    public Class interest() {
        return RegistryForbiddenServerRequest.class;
    }
}
